package com.jacky.ws.handler;

import com.jacky.ws.server.ChannelSupervise;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;

import static io.netty.handler.codec.http.HttpUtil.isKeepAlive;

public class HandshakeWebSocketHandler extends SimpleChannelInboundHandler<Object> {

    private final Logger LOG = LoggerFactory.getLogger(HandshakeWebSocketHandler.class);

    private WebSocketServerHandshaker handshaker;
    private final SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
    private final String webSocketPath;

    public HandshakeWebSocketHandler(String wsp) {
        this.webSocketPath = wsp;
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        LOG.info("收到消息：{}", msg);
        if (msg instanceof FullHttpRequest) {
            handleHttpRequest(ctx, (FullHttpRequest) msg);
        } else if (msg instanceof WebSocketFrame) {
            handleWebSocketFrame(ctx, (WebSocketFrame) msg);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        LOG.info("客户端加入连接:{}", ctx.channel());
        ChannelSupervise.addChannel(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        LOG.info("客户端断开连接:{}", ctx.channel());
        ChannelSupervise.removeChannel(ctx.channel());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
        // 判断是否为关闭连接指令
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), ((CloseWebSocketFrame) frame).retain());
            return;
        }
        if (frame instanceof PingWebSocketFrame) {
            LOG.info("服务端收到ping消息");
            ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
        }

        if (!(frame instanceof TextWebSocketFrame)) {
            LOG.info("本例仅支付文本消息,不支持二进制消息");
            throw new UnsupportedOperationException(
                    String.format("%s frame types not supported", frame.getClass().getName())
            );
        }

        String request = ((TextWebSocketFrame) frame).text();
        LOG.info("服务端收到消息:{}", request);
        TextWebSocketFrame respFrame = new TextWebSocketFrame(sdf.format(new Date()) + ctx.channel().id() + ":" + request);
        // 群发
//        ChannelSupervise.send2All(respFrame);
        ChannelSupervise.send2Others(respFrame, ctx.channel());
        // 返回给当前通知
//        ctx.channel().writeAndFlush(frame);
    }

    private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
        // 要求Upgrade为websocket,过滤掉get/post
        if (!req.decoderResult().isSuccess() || (!"websocket".equals(req.headers().get("Upgrade")))) {
            // 若不是webSocket方式,则创建BAD_REQUEST的req,返回给客户端
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
            return;
        }
        LOG.info("服务端收到webSocket建立链接消息");
        WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory(webSocketPath, null, false);
        handshaker = factory.newHandshaker(req);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), req);
        }
    }

    private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, DefaultFullHttpResponse resp) {
        if (resp.status().code() != 200) {
            ByteBuf byteBuf = Unpooled.copiedBuffer(resp.status().toString(), CharsetUtil.UTF_8);
            resp.content().writeBytes(byteBuf);
            byteBuf.release();
        }

        ChannelFuture future = ctx.channel().writeAndFlush(resp);
        if (!isKeepAlive(req) || resp.status().code() != 200) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }
}
